from flask import Flask, jsonify
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime, timedelta
import requests
import fitz  # PyMuPDF
import pytz
import os
from llm_model import llm_extract_resume
def TokenAccess(url):
    api_key = 'C8D208DA1A474D0396AD324A9E5BE288'
    api_secret = 'ECE597E884EE4755B71EE33F14150C7D83B7D1A4ADA749BF81932998F435EBA4'
    token_body = {
        "grant_type": "client_credentials",
        "app_key": api_key,
        "app_secret": api_secret
    }
    response = requests.post(url=url + '/token', data=token_body)
    if response.status_code == 200:
        token_json = response.json()
        access_token = token_json['access_token']
        print('Access Token:', access_token)
        return access_token
    else:
        print("Token Error")
        print(f"Error: {response.status_code}, {response.text}")
        return None


def GetApplicantList(url, startTime, endTime, access_token):
    api_headers = {
        'Authorization': f'Bearer {access_token}'
    }
    params = {
        "startTime": startTime,
        "endTime": endTime,
        "phaseCode": "S001",
        "statusCode": "U003"
    }
    api_response = requests.post(url=url + '/RecruitV6/api/v1/Apply/GetApplysByPhaseStatusCode', headers=api_headers,
                                 json=params)
    if api_response.status_code == 200:
        data = api_response.json()
        return data["data"]
    else:
        print("Applicant List Error")
        print(f"Error: {api_response.status_code}, {api_response.text}")
        return None


def ResumeExtraction(url, access_token, applyid):
    api_headers = {
        'Authorization': f'Bearer {access_token}'
    }
    api_url = url + '/RecruitV6/api/v1/Applicant/GetStandardResumeFileUrlByApplyId?applyId=' + str(applyid)
    r = requests.get(url=api_url, headers=api_headers)
    data = r.json()
    fileurl = data["data"]['downloadUrl']
    response = requests.get(url='https:' + fileurl)
    pdf_filename = 'downloaded_file.pdf'
    with open(pdf_filename, 'wb') as file:
        file.write(response.content)
    print(f"PDF 文件已保存为 {pdf_filename}")
    pdf_document = fitz.open(pdf_filename)
    text = ""
    for page_num in range(len(pdf_document)):
        page = pdf_document.load_page(page_num)
        text += page.get_text()
    pdf_document.close()
    print("提取文字内容成功")
    return text


def ConstructPrompt(url, access_token, applicant):
    headers = {
        'Authorization': f'Bearer {access_token}'
    }
    JD_Title = applicant["jobLite"]["jobTitle"]
    JD_Guid = applicant["jobLite"]["jobGuid"]
    params = {
        "jobIds": [JD_Guid]
    }
    response = requests.post(url=url + "/RecruitV6/api/v1/Job/GetJobListByIds", json=params, headers=headers)
    Job = response.json()
    duty = Job['data'][0]['duty']
    requirements = Job['data'][0]['require']
    text = ResumeExtraction(url, access_token, applicant["applyId"])
    JDPrompt = """你是一个具有30年招聘工作经历的资深招聘专家，具有寿险公司前中后台各业务线招聘交付经验，
        擅长通过阅读简历为企业挑选合适的候选人。希望您做简历内容的提取并针对公司的岗位职责进行匹配、通过匹配度进行评价并打分。
        你需要了解的背景信息如下：我所在的公司是一家养老保险公司。公司的用人导向是年轻（40岁以下）、教育背景良好（本科211、985以上或是研究生以上），工作经历避免频繁跳槽。当前的岗位职责是""" + duty
    prompt = """,并根据提供的简历模板提取简历内容，输出为json格式,具体格式如下：
        '''{
            "姓名" : "",
            "年龄" : "",
            "潜在风险" : "",
            "具体匹配项" : {
                "教育学历与专业" : {
                    "评分" : "",
                    "评分理由" : ""
                },
                "工作经历与项目经验" : {
                    "评分" : "",
                    "评分理由" : ""
                },
                "专业技能" : {
                    "评分" : "",
                    "评分理由" : ""
                },
                "组织管理能力" : {
                    "评分" : "",
                    "评分理由" : ""
                },
                "其他（软素质）" : {
                    "评分" : "",
                    "评分理由" : ""
                }
            },
            "总评分" : "",
            "总评分理由" : ""
        }'''" 
        应聘岗位、姓名到项目经验等基本信息要根据简历实际内容输出，不得揣测，年龄、最高学历就读时长的值必须是数字。提取出来的工作年限需要转换为数字。总结项目经验，要在150字左右。潜在风险等扩展能力需要根据简历扩展补充，不能为空，不得超过200字，
        具体匹配项中的评分都必须为数字0-20中的一个，简历中没有提及的项打0分。总评分是具体匹配项中的五项评分的值相加。评分理由需要根据匹配项逐项进行匹配，写清楚具体哪些匹配，哪些不匹配，要写清楚一些，每条100字左右。
        一定要注意，除了上述提及的json输出，一定不要有其他输出，一定一定不要加任何注释，不允许有任何//注释，一定要严格按照上面给定的json格式输出。简历如下："""
    prompt = JDPrompt + prompt
    return prompt, text


def UpdateField(url, access_token, applicant, score, reason, risk):
    headers = {
        'Authorization': f'Bearer {access_token}'
    }
    applyid = applicant["applyId"]
    param = {
        "applyList": [
            {
                "applyId": applyid,
                "fieldValues": {
                    "extaipingfen_432693_1029075836": score,
                    "extpingfenliyou_432693_1234838049": reason,
                    "extfengxiantishi_432693_2119307952": risk
                }
            }],
        "isSkipApplyLock": False,
        "isSkipApplicantLock": True
    }
    update_response = requests.post(url=url + "/RecruitV6/api/v1/Apply/UpdateApplyList", json=param, headers=headers)
    if update_response.status_code == 200:
        print("更新成功")
    else:
        print("更新失败，errcode：", update_response.status_code, update_response.text)


